import axios from 'axios'
import config from 'public/config/config.js'
import {message} from 'ant-design-vue'
import store from 'store'
const service = axios.create({
  baseURL:config.basePath,
  timeout:10000
})

axios.defaults.withCredentials = true// 携带cookie
// 请求拦截器
service.interceptors.request.use(
  config=>{
    const token = sessionStorage.getItem('token')
    if(token){
      config.headers['Authori-zation'] = 'Bearer ' + token
    }
    return config
  },
  error=>{
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    // console.log("response",response)
    let status = response.data?response.data.status:0
    return new Promise((resolve, reject) => {
        switch(status){
          case 500:
            resolve(response.data)
          break;
          case 400:
            store.commit('admin/outLogin')
            resolve(response.data)
          break;
          default:
            resolve(response.data)
          break;
        }
    });
  },
  error => {
    console.log('response-error',error)
    // message.error(error)
    message.error('请求失败')
  }
)

class request 
{
  static get(path,params){
    return new Promise((resolve, reject) => {
      service({
        url:path,
        method:"GET",
        params
      }).then(e=>{
        resolve(e)
      })
    });
  }

  static post(path,params){
    let data = new URLSearchParams();
    for(let i in params){
      data.append(i,params[i])
    }
    return new Promise((resolve, reject) => {
      service({
        url:path,
        method:"POST",
        data
      }).then(e=>{
        resolve(e)
      })
    });
  }
}

export default request